<template>
  <Form @submit="onSubmit" @failed="onFailed">
    <CellGroup title="基本信息" inset>
      <Field v-model.trim="form.name" label="种子名称" placeholder="可以不填,推送后自动获取" clearable autocomplete="no" />
      <Field v-model.trim="form.address" type="textarea" rows="3" label="下载链接" placeholder="下载链接" clearable
        autocomplete="no" required />
      <Field v-model="pickerForm.site" is-link readonly label="站点" placeholder="点击选择站点" @click="showPicker('site')" />
      <Field v-model="pickerForm.category" is-link readonly label="分类" placeholder="点击选择分类" @click="showPicker('category')"/>
      <!-- <Field
        v-model="pickerForm.client"
        is-link
        readonly
        label="下载器"
        placeholder="点击选择下载器"
        @click="showPicker('client')"
      /> -->
      <Field v-model.trim="form.description" type="textarea" rows="3" label="描述" placeholder="描述" maxlength="100"
        show-word-limit clearable autocomplete="no" />
      <Field label="自动链接">
        <template #input>
          <Switch v-model="form.autoLink" size="20"/> <span style="margin-left: 10px;font-size: 12px;color: gray;">仅限电影和剧集</span>
        </template>
      </Field>
    </CellGroup>
    <!-- <CellGroup title="自动链接" inset>
      <Field label="开启">
        <template #input>
          <Switch v-model="form.autoLink" size="20" :disabled="!autoLinkAllow"/> <span style="margin-left: 10px;font-size: 12px;color: gray;">仅限电影和剧集</span>
        </template>
      </Field>
      <Field v-model="pickerForm.library" is-link readonly label="媒体库" placeholder="点击选择媒体库"
        @click="showPicker('library')" :rules="[{ required: form.toLink, message: '请选择媒体库' }]" />
      <Field v-model.trim="form.toLink" label="子目录" placeholder="识别后自动获取" clearable autocomplete="no">
        <template #button>
          <Button size="small" type="success" icon="circle" @click="lintTolink" />
        </template>
      </Field>
    </CellGroup> -->
    <div style="margin: 16px;">
      <Button round block type="primary" native-type="submit" loading-type="spinner" :loading="submitting">
        保 存
      </Button>
    </div>
  </Form>

  <Popup v-model:show="showPickerFlag" position="bottom" :lazy-render="false">
    <Picker ref="picker" :columns="pickerColumns" @confirm="pickerConfirm" @cancel="showPickerFlag = false" />
  </Popup>

  <ActionSheet v-model:show="pushShow" title="推送下载"
    @close="emits('close')">
    <PushTorrent ref="pushTorrent" @close="()=>{planForm();pushShow = false;}" />
  </ActionSheet>
</template>
<script setup>
import { Form, Field, Switch, Cell, CellGroup, Button, Popup, ActionSheet, Picker, Dialog, Notify } from 'vant';
import PushTorrent from '@/mobile/Torrent/Push.vue'

import { reactive, ref, nextTick } from 'vue';

import BaseApi from '@/api/api.js'
import store from '@/store'
import { computed } from '@vue/reactivity';

const emits = defineEmits(['close'])


const modelId = '';
const form = reactive({
  autoLink: true,
});

const siteOptions = store.state.siteOptions;
const categoryOptions = store.state.categoryOptions;
const clientOptions = store.state.clientOptions;
const libraryOptions = store.state.libraryOptions;

const pickerForm = reactive({
  type: '',
  site: '',
  category: '',
  library: '',
});
const picker = ref(null);
const showPickerFlag = ref(false);
const pickerColumns = ref([])
const showPicker = (type) => {
  if (type === 'site') {
    pickerColumns.value = siteOptions.map(item => {
      return {
        text: item.name,
        value: item.id,
      }
    })
  } else if (type === 'category') {
    
    pickerColumns.value = categoryOptions.map(item => {
      return {
        text: item.name,
        value: item.id,
      }
    })
  } else if (type === 'client') {
    pickerColumns.value = clientOptions.map(item => {
      return {
        text: item.name,
        value: item.id,
      }
    })
  } else if (type === 'library') {
    pickerColumns.value = libraryOptions.map(item => {
      return {
        text: item.name,
        value: item.id,
      }
    })
  } else {
    pickerColumns.value = []
  }
  pickerForm.type = type;
  showPickerFlag.value = true;
}

const pickerConfirm = (value) => {
  if (pickerForm.type === 'site') {
    pickerForm.site = value.text;
    form.siteid = value.value;
  } else if (pickerForm.type === 'category') {
    pickerForm.category = value.text;
    form.categoryid = value.value;
  } else if (pickerForm.type === 'client') {
    pickerForm.client = value.text;
    form.clientid = value.value;
  } else if (pickerForm.type === 'library') {
    pickerForm.library = value.text;
    form.libraryid = value.value;
  }
  showPickerFlag.value = false;
}

const lintTolink = () => {
  if (form.name) {
    // 副标题（中），主标题（英）
    let title, title0
    if (form.name.indexOf('[') > 0) { // rss获取,不可包含'类型'
      title0 = form.name.slice(0, form.name.indexOf('['))
      const fMatch = form.name.match(/\[(.+?)\]/g)
      if (fMatch) title = fMatch[0].replace(/\[|\]/g, '')
    } else {
      title = form.name
    }
    // console.log('title:', title);
    // console.log('title0:', title0);
    let guess = ''
    const a = title.split(/\.| |_|\//);
    if (a) guess = a[0]
    let yearMatch = title.match(/(19|20)\d{2}/g)
    if (!yearMatch && title0) {
      yearMatch = title0.match(/(19|20)\d{2}/g)
    }
    if (yearMatch) guess += ` (${yearMatch[0]})`

    let seasonMatch = title.match(/S\d{1,2}/i)
    if (!seasonMatch && title0) {
      seasonMatch = title0.match(/S\d{1,2}/i)
    }
    if (seasonMatch) guess += `/Season ${parseInt(seasonMatch[0].slice(1))}`

    form.toLink = guess
  }
};

const pushTorrent = ref(null);
const submitting = ref(false);
const onSubmit = (values) => {
  // console.log('submit', form);

  // Dialog.confirm({
  //   title: '保存成功',
  //   message:
  //     '是否推送到下载器',
  // }).then(() => {
  //   // on confirm
  //   pushShow.value = true;
  // })
  // .catch(() => {
  //   // on cancel
  //   emits('close');
  // });

  // return;

  if (!form.address) {
    Notify({ type: 'warning', message: '请填写下载链接' });
    return;
  }

  submitting.value = true;
  BaseApi.save('torrent', form).then(response => {
    if (response.data.code === 1) {

      // Notify({ type: 'success', message: response.data.message?response.data.message:'保存成功' });

      Dialog.confirm({
        title: '保存成功',
        message: '是否推送到下载器',
        confirmButtonText: '推送',
        cancelButtonText: '暂不',
      }).then(() => {
        // on confirm
        pushShow.value = true;
        nextTick(() => {
          pushTorrent.value.initModel({
            id: response.data.data,
            clientid: '',
          });
        })
      })
        .catch(() => {
          planForm();
          // on cancel
          emits('close');
        });

    } else {
      Notify({ type: 'danger', message: `保存失败：${response.data.message}` });
    }
  }).catch((error) => {
    Notify({ type: 'danger', message: `保存失败：${error.message}` });
  }).then(() => {
    submitting.value = false;
  })
};

const onFailed = (errorInfo) => {
  // console.log('failed', errorInfo);
  // Notify({ type: 'danger', message: `保存失败：${errorInfo.errors.message}` });
};

const pushShow = ref(false);

const planForm = () => {
  form.id = '';
  form.name = '';
  form.address = '';
  form.siteid = '';
  form.categoryid = '';
  form.clientid = '';
  form.description = '';
  form.autoLink = true;
  form.libraryid = '';
  form.toLink = '';

  pickerForm.type = '';
  pickerForm.site = '';
  pickerForm.category = '';
  pickerForm.library = '';
}

const initModel = (item) => {
  planForm();
  if (item) {
    form.id = item.id;
    form.name = item.name;
    form.address = item.address;
    form.description = item.description;

    if (!item.id) { // RSS新增时
      // 记录种子Hash
      form.hashString = item.hash;
      // 自动匹配
      const sm = siteMatch(item.address);
      const cm = categoryMatch(item.categoryid);
      form.siteid = sm?.id
      form.categoryid = cm?.id

      pickerForm.site = sm?.name;
      pickerForm.category = cm?.name;
    }
  }
}


const siteMatch = (val) => {
  let matched
  if (val && siteOptions.length > 0) {
    const temp = splitSite(val)
    matched = siteOptions.find(s => {
      const sTemp = splitSite(s.address)
      return temp[1] === sTemp[1] && temp[2] === sTemp[2]
    })
  }
  return matched
};
const splitSite = (val) => {
  if (val) {
    const temp = val.replace('https://', '').replace('http://')
    return temp.split('/')[0].split('.')
  }
  return []
};
const categoryMatch = (val) => {
  let matched
  if (val && categoryOptions.length > 0) {
    matched = categoryOptions.find(c => val === c.folder)
  }
  return matched
};

defineExpose({
  initModel
})

// init functions

</script>